package h0825;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 合并两个有序链表
 * @date 2024/8/25 23:39
 */
public class MergeTwoLists {
    public static void main(String[] args) {
        ListNode a = new ListNode(1, new ListNode(2, new ListNode(5)));
        ListNode b = new ListNode(1, new ListNode(3, new ListNode(4)));
        ListNode res = mergeTwoLists(a, b);
        while (res != null) {
            System.out.println(res.val);
            res = res.next;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        }
        ListNode dummy = new ListNode(-1);
        ListNode prehead = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                prehead.next = list1;
                list1 = list1.next;
            } else {
                prehead.next = list2;
                list2 = list2.next;
            }
            prehead = prehead.next;
        }
        if (list1 != null) {
            prehead.next = list1;
        }
        if (list2 != null) {
            prehead.next = list2;
        }
        return dummy.next;
    }
}
